package com.aixin.project.servlet.admin;

import java.io.File;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.aixin.project.service.gensee.GenseeService;
import com.gensee.ws.siteadmin.WebcastCreationResult;
import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.log4j.Logger;
import org.apache.velocity.Template;
import org.apache.velocity.context.Context;

import com.aixin.project.conf.Configure;
import com.aixin.project.data.CommonConstants;
import com.aixin.project.data.Course;
import com.aixin.project.data.Expert;
import com.aixin.project.handler.CourseHandler;
import com.aixin.project.handler.ExpertHandler;
import com.aixin.project.util.AxMemcached;
import com.aixin.project.util.DateUtil;
import com.aixin.project.util.RequestUtil;

public class CourseAdminServlet extends AdminServlet {
    Logger logger = Logger.getLogger(CourseAdminServlet.class);

    @Override
    protected Template execute(HttpServletRequest request,
                               HttpServletResponse response, Context ctx) {
        ctx.put("navcourse",true);
        String method = RequestUtil.getStr(request, "method", "");
        if (method.equals("create")) {
            String filePath = this.getServletContext().getRealPath("\\")
                    + "images\\course\\";

            String lessoname = "";
            int lessonType = 0;
            String description = "";
            String startime = "";
            String endtime = "";
            long expertid = 0;
            double baseprice = 0;
            double addprice = 0;
            double pointprice = 0;
            String serviceName = "";
            String zzzPass = "";
            String jbPass = "";
            String cyzPass = "";
            if (ServletFileUpload.isMultipartContent(request)) {
                try {
                    // Create a factory for disk-based file items
                    DiskFileItemFactory factory = new DiskFileItemFactory();

                    // Set factory constraints
                    // factory.setSizeThreshold(4096); // 设置缓冲区大小，4kb
                    // factory.setRepository(tempPathFile);// 设置缓冲区目录

                    // Create a new file upload handler
                    ServletFileUpload upload = new ServletFileUpload(factory);

                    // Set overall request size constraint
                    upload.setSizeMax(4194304); // 设置最大文件尺寸，4MB

                    FileItem fw = null;
                    String[] files = null;
                    List<FileItem> items = upload.parseRequest(request);// 得到所有的文件
                    Iterator<FileItem> i = items.iterator();
                    while (i.hasNext()) {
                        FileItem fi = (FileItem) i.next();
                        if (fi.isFormField()) {
                            if ("lessoname".equals(fi.getFieldName())) {
                                lessoname = fi.getString("utf-8");
                            } else if ("lessonType".equals(fi.getFieldName())) {
                                lessonType = NumberUtils.toInt(
                                        (fi.getString("utf-8")), 2);
                            } else if ("description".equals(fi.getFieldName())) {
                                description = fi.getString("utf-8");
                            } else if ("startime".equals(fi.getFieldName())) {
                                startime = fi.getString("utf-8");
                            } else if ("endtime".equals(fi.getFieldName())) {
                                endtime = fi.getString("utf-8");
                            } else if ("expert".equals(fi.getFieldName())) {
                                expertid = NumberUtils.toInt((fi.getString("utf-8")),
                                        1);
                            } else if ("baseprice".equals(fi.getFieldName())) {
                                baseprice = NumberUtils.toDouble(
                                        fi.getString("utf-8"), 0);
                            } else if ("addprice".equals(fi.getFieldName())) {
                                addprice = NumberUtils.toDouble(fi.getString("utf-8"),
                                        0);
                            } else if ("pointprice".equals(fi.getFieldName())) {
                                pointprice = NumberUtils.toDouble(fi
                                        .getString("utf-8"), 0);
                            } else if ("serviceName".equals(fi.getFieldName())) {
                                serviceName = fi.getString("utf-8");
                            } else if ("zzzPass".equals(fi.getFieldName())) {
                                zzzPass = fi.getString("utf-8");
                            } else if ("jbPass".equals(fi.getFieldName())) {
                                jbPass = fi.getString("utf-8");
                            } else if ("cyzPass".equals(fi.getFieldName())) {
                                cyzPass = fi.getString("utf-8");
                            }
                        } else {
                            String filename = fi.getName();
                            files = filename.split("\\.");
                            fw = fi;

                        }

                    }

                    Date stardate = DateUtil.strToDate(startime);
                    Date enddate = DateUtil.strToDate(endtime);

                    Course c = new Course();
                    c.setTitle(lessoname);
                    c.setDescription(description);
                    c.setBaseprice(baseprice);
                    c.setAddprice(addprice);
                    c.setPointprice(pointprice);
                    c.setService(serviceName);
                    c.setCoursetype(lessonType);
                    c.setExpertid(expertid);

                    c.setStarttime(stardate);
                    c.setEndtime(enddate);
                    //create lession to gensee by webservice
                    WebcastCreationResult result = GenseeService.createLession(c);
                    if (StringUtils.trimToNull(result.getId()) != null) {
                        c.setGenseeid(result.getId());
                        c.setOrganizerurl(result.getOrganizerJoinUrl());
                        c.setWeburl(result.getAttendeeJoinUrl());
                        c.setClienturl(result.getPanelistJoinUrl());
                        c.setZzzpass(zzzPass);
                        c.setJbpass(jbPass);
                        c.setCyzpass(cyzPass);
                        int cid = CourseHandler.create(c);
                        if (cid != -1) {
                            ctx.put("createInfo", "创建课程成功，你可以继续添加课程!");
                           
                            if (fw != null) {
                                fw.write(new File(filePath + "c_" + cid + "."
                                        + files[1]));
                            }
                           AxMemcached.delete(CommonConstants.MKEY_E_ALL_COURSE_LIST+expertid);
                           AxMemcached.delete(CommonConstants.MKEY_E_COMING_COURSE_LIST+expertid);
                           AxMemcached.delete(CommonConstants.MKEY_COMING_COURSELIST);
                           AxMemcached.delete(CommonConstants.MKEY_HALL_EXPERTLIST);
                        } else {
                            ctx.put("createInfo", "创建课程失败..请检查填写信息是否正确或与管理员联系!");
                        }
                    } else {
                        System.out.println(result.getMessage());
                        ctx.put("createInfo", "远程创建课程失败..请检查填写信息是否正确或与管理员联系!");
                    }

                } catch (Exception e) {
                    logger.error("create course error : " + e.getMessage());
                }
            } else {
                List<Expert> expertList = ExpertHandler.expertList();
                String services[];
                String servername = (Configure.COURSE_SERVICE);
                if (servername.contains("|")) {
                    services = servername.split("\\|");
                } else {
                    services = new String[1];
                    services[0] = servername;
                }
                ctx.put("service", services);
                ctx.put("experts", expertList);
                return getTemplate("bg/creatlesson.vm");
            }

        } else if (method.equals("update")) {
            int cid = RequestUtil.getInt(request, "cid", -1);
            if (cid != -1) {
                Course course = CourseHandler.findByCid(cid);
                if (course == null) {
                    ctx.put("createInfo", "要修改的课程不存在!");
                    return getTemplate("bg/course.vm");
                }

                ctx.put("course", course);
                ctx.put("cid", cid);
                List<Expert> expertList = ExpertHandler.expertList();
                String services[];
                String servername = (Configure.COURSE_SERVICE);
                if (servername.contains("|")) {
                    services = servername.split("\\|");
                } else {
                    services = new String[1];
                    services[0] = servername;
                }
                ctx.put("service", services);
                ctx.put("experts", expertList);

                return getTemplate("bg/creatlesson.vm");
            } else {
            	int id = RequestUtil.getInt(request, "id", -1);
            
				Course course = CourseHandler.findByCid(id);
				if (course!=null) {
					
					String lessoname = RequestUtil.getStr(request, "lessoname","");
					int lessonType = RequestUtil.getInt(request, "lessonType",2);
					String description = RequestUtil.getStr(request,"description", "");
					String startime = RequestUtil.getStr(request, "startime","1971-01-01 00:00");
					String endtime = RequestUtil.getStr(request, "endtime","1971-01-01 00:00");
					long expertid = RequestUtil.getLong(request, "expert", 1);
					double baseprice = RequestUtil.getDouble(request,"baseprice", 0);
					double addprice = RequestUtil.getDouble(request,"addprice", 0);
					double pointprice = RequestUtil.getDouble(request,"pointprice", 0);
					String serviceName = RequestUtil.getStr(request,"serviceName", "gensee");
					String zzzPass= RequestUtil.getStr(request,"zzzPass", "");
					String jbPass= RequestUtil.getStr(request,"jbPass", "");
					String cyzPass= RequestUtil.getStr(request,"cyzPass", "");
					Date stardate = DateUtil.strToDate(startime);
					Date enddate = DateUtil.strToDate(endtime);
					
					/*try {
						
						lessoname=new String(lessoname.getBytes(),"UTF-8");
						description=new String(description.getBytes(),"UTF-8");
						System.out.println(lessoname+" : "+description);
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}*/

					Course c = new Course();
					c.setId(id);
					c.setTitle(lessoname);
					c.setDescription(description);
					c.setBaseprice(baseprice);
					c.setAddprice(addprice);
					c.setPointprice(pointprice);
					c.setService(serviceName);
					c.setCoursetype(lessonType);
					c.setExpertid(expertid);

					c.setStarttime(stardate);
					c.setEndtime(enddate);
					c.setZzzpass(zzzPass);
					c.setCyzpass(cyzPass);
					c.setJbpass(jbPass);
					
					if(lessoname!="" && description!=""){
					  int  stats = CourseHandler.update(c);
					  if (stats == 1) {
						 ctx.put("createInfo", "课程已更新");
						  AxMemcached.delete(CommonConstants.MKEY_E_ALL_COURSE_LIST);
	                      AxMemcached.delete(CommonConstants.MKEY_E_COMING_COURSE_LIST);
	                      AxMemcached.delete(CommonConstants.MKEY_COMING_COURSELIST);
	                      AxMemcached.delete(CommonConstants.MKEY_HALL_EXPERTLIST);

					  }
					}
				}else{
					ctx.put("createInfo", "无效操作");
				}
            }
        } else if (method.equals("del")) {
            long cid = RequestUtil.getLong(request, "cid", -1);
            if (cid != -1) {
                Course c = CourseHandler.find(cid);
                if (c != null) {
                    int stats = CourseHandler.delete(cid);
                    if (stats == 1) {
                        ctx.put("createInfo", "课程已成功删除!!");
                        AxMemcached.delete(CommonConstants.MKEY_E_ALL_COURSE_LIST);
                        AxMemcached.delete(CommonConstants.MKEY_E_COMING_COURSE_LIST);
                        AxMemcached.delete(CommonConstants.MKEY_COMING_COURSELIST);
                        AxMemcached.delete(CommonConstants.MKEY_HALL_EXPERTLIST);

                    }
                } else {
                    ctx.put("createInfo", "该课程不存在,无法删除!");
                }
            }
        }

    	int page=RequestUtil.getInt(request, "page", 1);
    	int stats=RequestUtil.getInt(request, "stats", 0);
    
		int pagenum=5;
		int maxpage=CourseHandler.maxpage(stats);
		List<Course> courseList = CourseHandler.listByPaggin(page,stats);
		ctx.put("stats", stats);
		ctx.put("courselist", courseList);
		ctx.put("curpage", page);
		ctx.put("pagenum", pagenum);
		ctx.put("maxpage", maxpage);
        return getTemplate("bg/course.vm");
    }
}
